package com.example.demo.wbgl.controller;


import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.demo.wbgl.entity.Blog;
import com.example.demo.wbgl.entity.Users;
import com.example.demo.wbgl.service.IBlogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author gongxl
 * @since 2021-06-01
 */
@RestController
@RequestMapping("/blog")
public class BlogController {

    @Autowired
    private IBlogService iBlogService;

    /**
     * 分页获取微博列表
     * @param current
     * @param size
     * @return
     */
    @RequestMapping("/getBlogPageList")
    public Page<Blog> getBlogPageList(@RequestParam(value = "current",defaultValue = "1")long current,
                                  @RequestParam(value = "size",defaultValue = "5")long size){
        Page page = new Page(current,size);
        Blog blog = new Blog();
        List<OrderItem> orderItems = OrderItem.descs("publishtime");
        page.setOrders(orderItems);
        List<Map<String,Object>> blogList=iBlogService.selectPageVo(page,blog);
        page.setRecords(blogList);
        return page;
    }

    /**
     * 添加微博
     * @param blog
     * @param session
     * @return
     */
    @RequestMapping("/addBlog")
    public Map addBlog(@RequestBody Blog blog, HttpSession session){
        Users users = (Users) session.getAttribute("users");
        blog.setUserid(users.getId());
        blog.setPublishtime(new Date());
        Map res = new HashMap();
        boolean save = iBlogService.save(blog);
        if(save){
            res.put("status",200);
            res.put("msg","用户保存成功");
        }else{
            res.put("status",300);
            res.put("msg","用户保存失败");
        }
        return res;
    }

    /**
     * 删除微博
     * @param id
     * @return
     */
    @RequestMapping("/delBlog")
    public Map delUser(@RequestParam("id") Long id){
        Map res = new HashMap();
        boolean save = iBlogService.removeById(id);
        if(save){
            res.put("status",200);
            res.put("msg","微博删除成功");
        }else{
            res.put("status",300);
            res.put("msg","微博删除失败");
        }
        return res;
    }
}

